package com.malty.mall.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.malty.mall.dao.ums.UmsAdminRoleMapper;
import com.malty.mall.domain.entity.ums.UmsAdminRoleRelation;
import com.malty.mall.domain.entity.ums.UmsRole;
import com.malty.mall.service.ums.IUmsAdminRoleService;
import com.malty.mall.service.ums.IUmsRoleService;
import com.malty.mall.util.PreconditionUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * @author malty
 */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class UmsAdminRoleServiceImpl extends ServiceImpl<UmsAdminRoleMapper, UmsAdminRoleRelation> implements IUmsAdminRoleService {
    private IUmsRoleService umsRoleService;

    @Autowired
    public void setUmsRoleService(IUmsRoleService umsRoleService) {
        this.umsRoleService = umsRoleService;
    }

    @Override
    public Boolean createOrUpdate(Integer uid, Integer roleId) {
        List<UmsRole> list = umsRoleService.list(Wrappers.<UmsRole>lambdaQuery().eq(UmsRole::getId, roleId));
        PreconditionUtils.check(ObjectUtils.isEmpty(list), "角色不存在");
        UmsAdminRoleRelation adminRoleRelation = new UmsAdminRoleRelation(uid, roleId);
        boolean saveOrUpdate = this.saveOrUpdate(adminRoleRelation, Wrappers.<UmsAdminRoleRelation>lambdaQuery()
                .eq(UmsAdminRoleRelation::getAdminId, uid).eq(UmsAdminRoleRelation::getRoleId, roleId));
        PreconditionUtils.check(!saveOrUpdate, "关联失败");
        return true;
    }

}
